package com.atgiogi.meiniantour.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.meinian.constant.MessageConstant;
import com.atguigu.meinian.constant.RedisMessageConstant;
import com.atguigu.meinian.service.MemberService;
import com.atguigu.meinian.util.MeiNianUtils;
import com.atguigu.meinian.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zbystart
 * @create 2021-06-25 15:30
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map, HttpServletResponse response) {
        // 验证验证码
        R r = null;
        String telephone = map.get("telephone");
        Map<String,String> result =  MeiNianUtils.checkCode(telephone,map.get("code"),jedisPool,RedisMessageConstant.SENDTYPE_LOGIN);
        if (result.get(MessageConstant.CODE_VERIFY_RESULT_KEY).equals(MessageConstant.CODE_VERIFY_SUCCESS)) {
            try {
                // 验证成功
                memberService.login(telephone);
                // 把登录信息保存到cookie中
                Cookie cookie = new Cookie("login_member_telephone",telephone);
                // 有效路径为当前项目
                cookie.setPath("/");
                // 有效时间为30天
                cookie.setMaxAge(30 * 24 * 60 * 60);
                response.addCookie(cookie);
                r = R.ok(MessageConstant.LOGIN_SUCCESS,null);
            } catch (Exception e) {
                e.printStackTrace();
                r = r.error(e.getMessage());
            }
        } else {
            // 验证失败
            r = R.error(result.get(MessageConstant.CODE_VERIFY_MESSAGE_Key));
        }
        return r;
    }

    @GetMapping("/sendCode")
    public R sendCode(String telephone) {

        try {
            // 发送短信验证码
            MeiNianUtils.sendCode(telephone,4,jedisPool, RedisMessageConstant.SENDTYPE_LOGIN,5 * 60);
            return R.ok(MessageConstant.SEND_VALIDATECODE_SUCCESS,null);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

}
